package com.ztools.pc.service.impl.sys;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ztools.common.model.pc.sys.Permission;
import com.ztools.common.model.pc.sys.Role;
import com.ztools.common.model.pc.sys.RolePermission;
import com.ztools.common.model.pc.sys.UserRole;
import com.ztools.common.util.common.PageUtil;
import com.ztools.common.util.pc.RedisUtil;
import com.ztools.pc.async.RedisAsync;
import com.ztools.pc.mapper.sys.RolePermissionMapper;
import com.ztools.pc.service.sys.PermissionService;
import com.ztools.pc.service.sys.RolePermissionService;
import com.ztools.pc.service.sys.RoleService;
import com.ztools.pc.service.sys.UserRoleService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author:一口香菜
 * @Date: 2023/3/4  15:22
 * @Version 1.0
 */
@Transactional
@Service
public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionMapper, RolePermission> implements RolePermissionService {

    @Resource
    private PermissionService permissionService;
    @Resource
    private UserRoleService userRoleService;
    @Resource
    private RoleService roleService;
    @Resource
    private RolePermissionMapper rolePermissionsMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RolePermissionMapper rolePermissionMapper;
    @Resource
    private RedisAsync redisAsync;

    @Override
    public List<Permission> findPerByRoleId(Long userId) {
        String key = RedisUtil.PERMISSIONS + userId;
        // 判断redis里面是否有权限
        String permissionStr = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotEmpty(permissionStr)) {
            return JSONUtil.toList(JSONUtil.parseArray(permissionStr), Permission.class);
        }
        QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
        QueryWrapper<RolePermission> rolePermissionQueryWrapper = new QueryWrapper<>();
        List<Permission> permissionList = new ArrayList<Permission>();
        userRoleQueryWrapper.eq("user_id", userId);
        // 查询用户的所有角色
        List<UserRole> userRoleList = userRoleService.list(userRoleQueryWrapper);
        if (ArrayUtil.isNotEmpty(userRoleList)) {
            List<Long> roleIdList = userRoleList.stream().map(UserRole::getRoleId).collect(Collectors.toList());
            List<Role> roleList = roleService.findByIds(roleIdList);
            String content = stringRedisTemplate.opsForValue().get(RedisUtil.ADMIN_CONTENT) == null ? "admin" : stringRedisTemplate.opsForValue().get(RedisUtil.ADMIN_CONTENT);
            boolean isAmin = false;
            // 超级管理员
            if (ArrayUtil.isNotEmpty(roleList)) {
                for (Role role : roleList) {
                    if (content != null && !role.getRoleName().contains(content) && !role.getRoleName().contains(content)) {
                        continue;
                    }
                    isAmin = true;
                    permissionList = permissionService.list();
                    break;
                }
                // 非超级管理员
                if (!isAmin) {
                    // 通过角色ID集合查询权限
                    List<Long> permissionIdList = rolePermissionsMapper.listByRoleIds(roleIdList);
                    permissionList = permissionService.findByIds(permissionIdList);
                }
            }
            if (ArrayUtil.isNotEmpty(permissionList)) {
                stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(permissionList), 1, TimeUnit.HOURS);
            }
            return permissionList;
        }
        return null;
    }

    /**
     * 分页查询
     *
     * @param pageUtil
     * @return
     */
    @Override
    public Page<RolePermission> findList(@RequestBody PageUtil<RolePermission> pageUtil) {
        List<OrderItem> orders = new ArrayList<>();
        QueryWrapper<RolePermission> queryWrapper = new QueryWrapper<>(pageUtil.getParams());
        Page<RolePermission> pages = new Page<>(pageUtil.getPage(), pageUtil.getSize());
        // 排序数据  StrUtil.toUnderlineCase huTools将驼峰装换为下划线格式
        orders.add(new OrderItem(StrUtil.toUnderlineCase(pageUtil.getSortName()), "asc".equals(pageUtil.getSortOrder())));
        pages.setOrders(orders);
        return page(pages, queryWrapper);
    }

    @Override
    public boolean addList(List<RolePermission> rolePermissionList) {
        boolean b = false;
        // 删除角色的全部权限
        rolePermissionMapper.deleteByRoleId(rolePermissionList.get(0).getRoleId());
        if (rolePermissionList.get(0).getPermissionId() == null) {
            return true;
        }
        b = saveBatch(rolePermissionList);
        if (b) {
            // 删除缓存
            redisAsync.doAfterPermissionChange();
        }
        return b;
    }

}
